/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.far.aus.adm.excel;

import com.far.lib.BaseDatos;
import com.far.lib.Excel;
import com.far.lib.Fecha;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Jorge
 */
public class ExcelConsolidadoAuspicio extends HttpServlet {

    private String _ip = null;
    private int _puerto = 5432;
    private String _db = null;
    private String _usuario = null;
    private String _clave = null;
    
    public void init(ServletConfig config) throws ServletException
    {
        this._ip = config.getServletContext().getInitParameter("_IP");
        this._puerto = Integer.parseInt(config.getServletContext().getInitParameter("_PUERTO"));
        this._db = config.getServletContext().getInitParameter("_DB");
        this._usuario = config.getServletContext().getInitParameter("_USUARIO");
        this._clave = config.getServletContext().getInitParameter("_CLAVE");
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if(request.getHeader("User-Agent").toLowerCase().contains("windows")){
            response.setContentType("application/vnd.ms-excel;");
            response.setHeader("Content-disposition", "inline; filename=PlanMercadeoGastos.xls;");
        }else{
            response.setContentType("text/xml;");
            response.setHeader("Content-disposition", "attachment; filename=PlanMercadeoGastos.ods;");
        }
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "Mon, 01 Jan 2001 00:00:01 GMT");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Cache-Control", "must-revalidate");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();

        String fecha_ini = request.getParameter("repFi");
        String fecha_fin = request.getParameter("repFf");
        String id_tipo_plan = request.getParameter("repIdTP");
        String estado = request.getParameter("repEst");
        String proveedor = request.getParameter("provReporte")!=null ? request.getParameter("provReporte") : "";
        String num_auspicio = request.getParameter("repNum_aus");
        
        String where = "where";
        
        if(fecha_ini.compareTo("")!=0 && fecha_fin.compareTo("")!=0){
             where += " CONVERT(VARCHAR, fecha_creacion, 103) between '"+Fecha.ISOaSQL(fecha_ini)+"' and '"+Fecha.ISOaSQL(fecha_fin)+"'";
        }else{
            if(fecha_ini.compareTo("")!=0 && fecha_fin.compareTo("")==0){
                 where += " CONVERT(VARCHAR, fecha_creacion, 103) >= '"+Fecha.ISOaSQL(fecha_ini)+"'";
            }else{
                if(fecha_ini.compareTo("")==0 && fecha_fin.compareTo("")!=0){
                     where += " CONVERT(VARCHAR, fecha_creacion, 103) <= '"+Fecha.ISOaSQL(fecha_ini)+"'";
                }
            }
        }
        
        if(id_tipo_plan.compareTo("0")!=0){
             where += (where.compareTo("where")!=0 ? " and" : "") + " id_tipo_plan='"+id_tipo_plan+"'";
        }
        if(estado.compareTo("")!=0){
             where += (where.compareTo("where")!=0 ? " and" : "") + " estado='"+estado+"'";
        }
        if(proveedor.compareTo("0")!=0 && proveedor.compareTo("")!=0){
             where += (where.compareTo("where")!=0 ? " and" : "") + " proveedor='"+proveedor+"'";
        }
        
        if(where.compareTo("where")==0){
            where = "";
        }
        
        if(num_auspicio.compareTo("")!=0){
             where = "where num_auspicio='"+num_auspicio+"'";
        }

        BaseDatos objDB = new BaseDatos(this._ip, this._puerto, this._db, this._usuario, this._clave);
        ResultSet registros = objDB.consulta("select num_auspicio, plan_actividad, txt_fecha_creacion, txt_fecha_confirmacion, txt_fecha_anulacion, "+
        "txt_estado, proveedor, tipo_plan, txt_tipo_confirmacion, subtotal_act, iva_act, total_act, forma_pago, usuario_creacion " +
        "from vta_auspicio_actividad_detalle " +
        where +
        " order by num_auspicio");
        
        String subtitulo = "Consolidado de Auspicios";
        String [] cabTabla = new String [] {"No. DE AUSPICIO", "PLAN DE ACTIVIDADES", "FECHA DE CRACION", "FECHA DE CONFIRMACION", 
            "FECHA DE ANULACION", "ESTADO", "PROVEEDOR", "TIPO DE AUSPICIO", "TIPO DE CONFIRMACION", "SUB-TOTAL", "IVA", "TOTAL", 
            "FORMA DE PAGO", "USUARIO DE CREACION"};
        String [] tipos = new String [] {"String", "String", "String", "String", "String", "String", "String", "String",
            "String", "Number", "Number", "Number", "String", "String"};
        
        try{
            Excel reporte = new Excel(subtitulo);
            String xls = reporte.lista(registros, cabTabla, tipos);
            out.print(xls);
            registros.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        objDB.cerrar();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
